const { spawn } = require("child_process");
var cmd = "php";
// test /Users/tools/php8.1/bin/php
if (process.argv[2]) {
  cmd = process.argv[2];
}

var phpWorkers = [];
var workersNum = 10;

// http://nodejs.cn/api/
var readCallback = function () {};

function startWorker(workerIndex) {
  phpWorkers[workerIndex] = spawn(cmd, ["pm.php"]);

  function start(workerIndex) {
    var buffer = "";
    phpWorkers[workerIndex].stdout.on("data", (data) => {
      buffer += data;

      var bufferIndex = buffer.indexOf("\n");
      while (bufferIndex != -1) {
        onStdout(buffer.substr(0, bufferIndex));
        buffer = buffer.substr(bufferIndex + 1);
        bufferIndex = buffer.indexOf("\n");
      }
    });

    phpWorkers[workerIndex].stderr.on("data", (data) => {
      onStderr(data);
    });

    phpWorkers[workerIndex].on("close", (code) => {
      onClose(code);
    });
  }

  function onStderr(data) {
    console.error(`stderr: ${data}`);
  }

  function onStdout(data) {
    console.log(`${workerIndex} onStdout: ${data}`);
    try {
      data = JSON.parse(data);
      readCallback(data);
    } catch (e) {
      return;
    }
  }

  function onClose(code) {
    console.log(`子进程退出，使用退出码 ${code}`, new Date().toLocaleString());
    phpWorkers[workerIndex] = spawn(cmd, ["pm.php"]);
    start(workerIndex);
  }

  start(workerIndex);
}

function write(request_id, type, data) {
  var json = { request_id, type, data };
  json = JSON.stringify(json);
  //todo 判断子进程退出
  phpWorkers[request_id % workersNum].stdin.write(json + "\n");
}

function setReadCallback(callback) {
  readCallback = callback;
}

for (var i = 0; i < workersNum; i++) {
  startWorker(i);
}

// {request_id: 1, type: 'request', date: {}}
//type (request, response, file_get_contents)
module.exports = {
  write,
  setReadCallback,
};
